package com.leyou.gateway.filter;

import com.leyou.common.pojo.UserInfo;
import com.leyou.common.utils.CookieUtils;
import com.leyou.common.utils.JwtUtils;
import com.leyou.gateway.config.FilterProperties;
import com.leyou.gateway.config.JwtProperties;
import com.netflix.zuul.ZuulFilter;
import com.netflix.zuul.context.RequestContext;
import com.netflix.zuul.exception.ZuulException;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.http.HttpStatus;
import org.springframework.stereotype.Component;

import javax.servlet.http.HttpServletRequest;
import java.util.List;
//网关登录拦截器，对白名单执行放行
@Component
@EnableConfigurationProperties({JwtProperties.class, FilterProperties.class})
public class LoginFilter extends ZuulFilter {
    @Autowired
    private JwtProperties jwtProperties;
    @Autowired
    private FilterProperties filterProperties;

    @Override
    public String filterType() {
        return "pre";
    }

    //执行顺序，0为不执行，数字越小，执行优先级越高
    @Override
    public int filterOrder() {
        return 10;
    }

    /**
     * 将白名单遍历与url比较，有则false，不继续执行run（），放行；无则true，执行run进行登录校验
     * @return
     */
    @Override
    public boolean shouldFilter() {
        //获取白名单
        List<String> allowPaths = this.filterProperties.getAllowPaths();
        //初始化zuul的上下文
        RequestContext context = RequestContext.getCurrentContext();
        //获取request对象
        HttpServletRequest request = context.getRequest();
        //获取请求路径的url
        String url = request.getRequestURL().toString();
        //遍历白名单，与url比较，有的话就返回false，不执行过滤 run方法
        for (String allowPath : allowPaths) {
            if (StringUtils.contains(url,allowPath)){
                return false;
            }
        }
        return true;
    }

    /**
     * 登录校验token。zuul上下文获取request,获取token，通过工具类以及登录者信息UserInfo，包括id和username
     * @return
     * @throws ZuulException
     */
    @Override
    public Object run() throws ZuulException {
        //初始化zuul的上下文
        RequestContext context = RequestContext.getCurrentContext();
        //获取request对象
        HttpServletRequest request = context.getRequest();

        //cookieUtils工具类
        String token = CookieUtils.getCookieValue(request, this.jwtProperties.getCookieName());

        //这个token验证可以不要，要了更完美，因为本身会判断一次，不要，代码更简洁
       /* if (StringUtils.isBlank(token)){
           context.setSendZuulResponse(false);
           context.setResponseStatusCode(HttpStatus.UNAUTHORIZED.value());
        }*/

        try {
            //通过校验，则放行，什么都不做
            JwtUtils.getInfoFromToken(token, this.jwtProperties.getPublicKey());
        } catch (Exception e) {
            //校验出现异常，返回未认证信息，要求重新登录
            e.printStackTrace();
            context.setSendZuulResponse(false);
            //设置响应状态码
            context.setResponseStatusCode(HttpStatus.UNAUTHORIZED.value());
        }
        return null;
    }
}
